package com.netease.dylan;

import java.io.IOException;
import java.net.InetSocketAddress;

import net.spy.memcached.CASResponse;
import net.spy.memcached.CASValue;
import net.spy.memcached.MemcachedClient;

public class Main {

	private static MemcachedClient client = null;

	static {
		try {
			client = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		} catch (IOException o) {
		}
	}

	public static void main(String[] args) throws Exception {

		client.set("numberss", 1800, 1);
		/*
		CASValue<Object> uniqueValue = client.gets("numberss");
		CASResponse response = client.cas("numberss", uniqueValue.getCas(), (Integer) uniqueValue.getValue() + 1);
		System.out.println(uniqueValue.getValue());
		System.out.println(response.toString());
		*/
		Main testObj = new Main();
		for (int i = 0; i < 10; i++) {
			testObj.new ThreadTest("Thread-" + (i + 1)).start();
		}
	}

	private class ThreadTest extends Thread {

		private MemcachedClient client = null;

		ThreadTest(String name) throws IOException {
			super(name);
			client = new MemcachedClient(new InetSocketAddress("localhost", 11211));
		}

		public void run() {
			int i = 0;
			int success = 0;
			while (i < 10) {
				i++;
				/*
				 * client.gets(key): Gets (with CAS support) with a single key using the default transcoder.
				 * CASValue: A value with a CAS identifier.
				 * CASValue.getCas(): Get the CAS identifier.
				 * CASValue.getValue(): Get the object value.
				 * client.cas(key, casId, value): Perform a synchronous CAS operation with the default transcoder.
				 */
				CASValue<Object> uniqueValue = client.gets("numberss");
				CASResponse response = client.cas("numberss", uniqueValue.getCas(), (Integer) uniqueValue.getValue() + 1);
				if (response.toString().equals("OK")) {
					success++;
				}
				if (i == 10)
					System.out.println(Thread.currentThread().getName() + " " + i + " time " + " update oldValue : " + uniqueValue.getValue() + " , result : " + response);
			}
			if (success < 10) {
				Count.incr(10 - success);
				System.out.println("Test counter: " + Count.get());
			}
		}
	}

	public static class Count {
		private static int counter = 0;

		public static void incr(int x) {
			counter += x;
		}

		public static int get() {
			return counter;
		}
	}
}